<script setup lang="ts">
import { onShow, onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
import { searchDataApi } from '@/apis/search';
import type { SkuInfo } from '@/types/SkuModule';
import type { SearchParams, attrParams, attr } from '@/types/SearchParams';
import type { SearchResult } from "@/types/SearchResult"

const { safeAreaInsets } = uni.getSystemInfoSync()
// 接收跳转数据
const query = defineProps<{
  condition: string,
  categoryId:number,
}>()

// 参数
const searchParams: Required<SearchParams> = {
  // 关键字
  keyword: query.condition,
  // 三级分类id
  categoryId: query.categoryId,
  // 价格排序标识
  priceSort: null,
  // 品牌集合
  brandId: null,
  // 参数搜索的属性集合
  attributes: null,
  // 页码
  pageNum: 1,
}

// 获取数据
const skuInfoList = ref<SkuInfo[]>([])
const searchData = ref<SearchResult<SkuInfo>>()
// 结束标识
const finish = ref(2);
const getSearchData = async () => {
  // 退出分页判断
  if (finish.value === 1) {
    return
  }
  const res = await searchDataApi(searchParams)
  searchData.value = res.data
  console.log(searchData.value)
  if (searchData.value.skus) {
    skuInfoList.value.push(...searchData.value.skus);
    if (searchParams.pageNum < searchData.value.pages) {
      searchParams.pageNum++;
      finish.value = 2;
    } else {
      finish.value = 1;
    }
  }
}

// 滚动触底事件
const onScrolltolower = () => {
  getSearchData()
}

// 返回搜索框的按钮
const handleback = () => {
  uni.navigateBack({
    delta: 1
  });
}

// 获得焦点时返回搜索页
const handleGoSearch = () => {
  if(getCurrentPages().length >2){
      uni.navigateBack({
      delta: 1
    });
  }else {
    uni.navigateTo({url:'/pagesSearch/search/search'})
  }
  
}

// 选择品牌
const handleSelectBrand = (brandId:number) =>{
  searchParams.brandId = brandId;
  searchParams.attributes = null;
  selectValue.value = []
  temporaryValue.value = []
  backValue = []
  searchParams.pageNum = 1;
  skuInfoList.value = [];
  finish.value = 2;
  higheShow.value = 0;
  selectShow.value = false;
  getSearchData()
}

// 高亮
const higheShow = ref(0)
// 显示选项
const selectShow = ref(false)
// 可选数据
const selectValue = ref<Array<attrParams>>([])
// attrId标志
const attrId = ref<number>()
const openPopup = (attributeId:number, value:string[]) => {
  selectValue.value = []
  attrId.value = attributeId
  if(higheShow.value === attributeId){
    higheShow.value = 0;
    selectShow.value = false;
  }else{
    higheShow.value = attributeId;
    selectShow.value = true;
    }
  // 构建可选数据
  value.forEach(item => {
    selectValue.value.push({
      attributeId:attributeId,
      value:item,
    })
  })
}

// 临时选择
const temporaryValue = ref<attrParams[]>([])
const handleSelect = (item:attrParams) => {
  const index = temporaryValue.value.findIndex(obj => obj.attributeId === item.attributeId && obj.value === item.value)
  if(index === -1){
    temporaryValue.value.push(item)
  }else{
    temporaryValue.value.splice(index, 1);
  }
}

// 判断是否选择
const handleIsExist = (item:attrParams) => {
  const isExist = temporaryValue.value.findIndex(obj => obj.attributeId === item.attributeId && obj.value === item.value)
  if(isExist === -1){
    return false
  }
  return true
}

// 关闭遮罩层
let backValue : attrParams[] = []
const colsePopup = () => {
  temporaryValue.value = JSON.parse(JSON.stringify(backValue))
  higheShow.value = 0;
  selectShow.value = false;
  selectValue.value = []
}

// 点击确定
const handleConfim = () =>{
  // 深拷贝，临时数据备份
  backValue = JSON.parse(JSON.stringify(temporaryValue.value))
  const result = buildData()

  searchParams.attributes = result;
  selectValue.value = []
  searchParams.pageNum = 1;
  skuInfoList.value = [];
  finish.value = 2;
  higheShow.value = 0;
  selectShow.value = false;
  getSearchData()
}

const showTitle = (attributeId: number) =>{
  const existingObj = backValue.find(obj => obj.attributeId === attributeId)
  if(existingObj){
    return true;
  }
  return false;
}

// // 点击重置
const handleRefresh =() =>{
  temporaryValue.value = temporaryValue.value.filter(item => item.attributeId !== attrId.value)
  backValue = JSON.parse(JSON.stringify(temporaryValue.value))
  const result = buildData()

  searchParams.attributes = result;
  selectValue.value = []
  searchParams.pageNum = 1;
  skuInfoList.value = [];
  finish.value = 2;
  higheShow.value = 0;
  selectShow.value = false;
  getSearchData()
}

// 组合发送的数据
const buildData = () => {
  return temporaryValue.value.reduce((acc:attr[], curr) => {
    const existingObj = acc.find(obj => obj.attributeId === curr.attributeId);
    if (existingObj) {
      const isExistValue = existingObj.value.includes(curr.value)
      if(!isExistValue){
        existingObj.value.push(curr.value);
      }
    } else {
      // 否则，创建一个新的对象
      acc.push({attributeId: curr.attributeId, value: [curr.value]});
    }
    return acc;
  }, []);
}

onLoad(() => {
  getSearchData()
})
</script>

<template>
  <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top! + 'px' }">
    <view class="search-css" @tap="handleback">
      <text class="icon-zuojiantou1" style="font-size: 50rpx;"></text>
    </view>
    <view class="search">
      <text class="icon-sousuo icon-css"></text>
      <view class="input-content"  @tap="handleGoSearch">{{ query.condition }}</view>
      <view class="view-input" @tap="handleGoSearch"></view>
    </view>
  </view>
  <view class="viewport">
    <view class="content_css">
      <scroll-view v-if="skuInfoList.length > 0" scroll-y class="scroll_y" @scrolltolower="onScrolltolower">
        <view >
          <scroll-view scroll-x style="height: 145rpx;width:100%;white-space: nowrap;" v-if="searchData!.brands.length > 1"> 
          <view v-for="item in searchData?.brands" class="brand_x">
            <view style="width: 100%;height: 100%;display: flex;flex-direction: column;padding: 6rpx;" @tap="handleSelectBrand(item.brandId)">
              <image class="image" mode="aspectFill" :src="item.logoUrl" style="width: 100%;height: 95rpx;"></image>
              <view class="show_brand_title">{{ item.brandName }}</view>
            </view>
          </view>
        </scroll-view>
        </view>
        
        <view style="height: 100%;position: relative;">
          <scroll-view scroll-x class="scroll_x">
          <view v-for="item in searchData?.attributes" class="scroll-x-item" :class="[item.attributeId === higheShow? 'show_color':'']" :key="item.attributeId" @tap="openPopup(item.attributeId, item.value)">
            <view :class="[showTitle(item.attributeId)? 'title_show':'']">{{ item.attributeName }}</view>
          </view>
        </scroll-view>
        
          <view class="popup_css" v-if="selectShow">
            <scroll-view scroll-y class="popup_scroll">
              <view v-for="item, index in selectValue" class="popup_cont_css" :key="index">
                <view @tap="handleSelect(item)" :key="item.value" class="select_css" :class="[handleIsExist(item)? 'select_text':'']">{{ item.value }}</view>
              </view>
            </scroll-view>
            <view class="view_button">
              <button @tap="handleRefresh" class="popup_button_left">重置</button>
              <button @tap="handleConfim" class="popup_button_right">确定</button>
            </view>
          
        </view>
        <!-- 遮罩层 -->
        <view style="background-color: rgba(56, 56, 56, 0.404);height: 100%;position: absolute;z-index: 90;width: 100%;" v-if="selectShow" @tap="colsePopup"/>
        <view class="guess">
          <navigator class="guess-item" v-for="item in skuInfoList" :key="item.skuId"
            :url="`/pages/goods/goods?skuId=${item.skuId}`">
            <image class="image" mode="aspectFill" :src="item.skuDefaultImg"></image>
            <view class="name">{{ item.spuTitle }}</view>
            <view class="price">
              <text class="small">¥</text>
              <text>{{ item.price.toFixed(2) }}</text>
            </view>
          </navigator>
          <view class="loading_css">
            <uni-load-more v-if="finish === 0" iconType="circle" status="loading"/>
            <uni-load-more v-else-if="finish === 1" iconType="circle" status="noMore" />
          </view>
        </view>
    </view>
      </scroll-view>

      <view v-else class="data_none_css">
        <image src="../../static/images/no-search.png" mode="scaleToFill" style="height: 510rpx;width: 510rpx;"/>
        <view class="none_tip">没有找到你想要的商品，换个搜索词试试</view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
page {
  height: 100%;
  background-color: rgb(244, 245, 247);
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.navbar {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  background-color: rgb(242, 241, 239);
  padding-right: 100px;

  .search-css{
    width: 40rpx;
    margin-left: 10rpx;
    height: 64rpx;
    line-height: 64rpx;
    margin: 4px 0 10px 8px;
  }

  .search {
    position: relative;
    width: 100%;
    margin: 4px 0 10px 11px;

    .icon-css{
      position: absolute;
      top: 18rpx;
      left: 20rpx;
      font-size: 28rpx;
    }

    .input-content{
      position: absolute;
      height: 64rpx;
      line-height: 64rpx;
      top: 0;
      left: 64rpx;
      font-size: 28rpx;
      max-width: 85%;
      overflow:hidden; 
      text-overflow:ellipsis;
      white-space:nowrap;
    }

    .view-input{
      background-color: white;
      height: 64rpx;
      padding-left: 56rpx;
      border-radius: 32rpx;
      font-size: 25rpx;
    }
  }
}

.content_css {
  flex: 1;
  overflow: hidden;
}

.data_none_css {
  text-align: center;
  padding-top: 80rpx;
  .none_tip {
    text-align: center;
    font-size: 22rpx;
    color: #666;
  }
}

.scroll_y {
  height: 100%;
  overflow: hidden;
  position: relative;

  .brand_x{
    width: 110rpx;
    height: 125rpx;
    margin-top: 10rpx;
    text-align: center;
    display: inline-block;
    background-color: white;
    margin-left: 20rpx;
    border-radius: 10rpx;

    .show_brand_title {
      text-align: center;
      line-height: 30rpx;
      font-size: 20rpx;
      height: 30rpx;
      overflow:hidden; 
      text-overflow:ellipsis;   
      white-space:nowrap;  
    }
  }

  .scroll_x {
    position: absolute;
    right: 0;
    left: 0;
    white-space: nowrap;
    height: 90rpx;
    width: 100%;
    background-color: white;
    z-index: 99;

    .scroll-x-item {
      display: inline-block;
      width: 150rpx;
      height: 60rpx;
      margin-top: 15rpx;
      line-height: 60rpx;
      text-align: center;
      font-size: 26rpx;
      border-radius: 10rpx;
      margin-left: 20rpx;
      background-color: rgb(244, 245, 247);

      .title_show{
        height: 100%;
        width: 100%;
        background-color: rgb(250, 222, 222);
        border-radius: 10rpx;
        color: rgb(247, 88, 88);
      }
    }

    .show_color{
      background-color: rgb(230, 231, 233);
    }
  }
}

.scroll_x .scroll-x-item:last-child{
  margin-right: 20rpx;
}

.guess {
  width: 100%;
  position: absolute;
  top: 90rpx;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 15rpx 20rpx 0;
  z-index: 1;

  .guess-item {
    width: 345rpx;
    padding: 24rpx 20rpx 20rpx;
    margin-bottom: 20rpx;
    border-radius: 10rpx;
    overflow: hidden;
    background-color: #fff;
  }

  .loading_css{
    text-align: center;
    width: 100%;
  }

  .image {
    width: 304rpx;
    height: 304rpx;
  }

  .name {
    height: 75rpx;
    margin: 10rpx 0;
    font-size: 26rpx;
    color: #262626;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .price {
    line-height: 1;
    padding-top: 4rpx;
    color: #cf4444;
    font-size: 28rpx;
  }

  .small {
    font-size: 80%;
  }
}

.popup_css {
  position: absolute;
  left: 0;
  top: 90rpx;
  z-index: 95;
  width: 100%;
  height: 520rpx;
  padding: 10rpx;
  background-color: rgb(244, 245, 247);
  border-bottom-left-radius: 20rpx;
  border-bottom-right-radius: 20rpx;
  .popup_scroll {
    width: 100%;
    height: 420rpx;
    border-bottom-left-radius: 20rpx;
    border-bottom-right-radius: 20rpx;

    .popup_cont_css{
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      .select_text{
        color: red;
      }

      .select_css{
        width: 48%;
        font-size: 25rpx;
        margin-bottom: 15rpx;
        height: 70rpx;
        line-height: 70rpx;
        padding-left: 5rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }
  }

  .view_button {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 90rpx;
  }

  .popup_button_left {
    display: flex;
    justify-content: center;
    align-items: center;
    color: red;
    width: 90%;
    height: 70%;
    font-size: 32rpx;
    border: 1px solid red;
    border-radius: 50rpx 0 0 50rpx;
    background-color: white;
  }

  .popup_button_right {
    display: flex;
    justify-content: center;
    align-items: center;
    color: white;
    width: 90%;
    height: 70%;
    font-size: 32rpx;
    border-radius: 0 50rpx 50rpx 0;
    background-color: red;
  }
}
// 加载提示文字
.loading-text {
  text-align: center;
  font-size: 28rpx;
  color: #666;
  padding: 20rpx 0;
}
</style>